#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-18 10:14
# @Author  : wsh
# @File    : exception_handlers.pyfrom fastapi import HTTPException
import re
from fastapi import HTTPException
from starlette.requests import Request

from model.db import reservoir_sensitivity
from util.custom_response import error_res, ErrorCode


class AllException(HTTPException):

    def __init__(self, message):
        super().__init__(status_code=500, detail=message)


class AllExceptionHandler:
    """ 处理所有异常 """

    async def __call__(self, request: Request, exc):
        print(exc.detail)
        return error_res(ErrorCode.SERVER)


class PwdNotMate(HTTPException):
    """ 密码错误异常 """

    def __init__(self, message: str):
        super().__init__(status_code=200, detail=message)


class PwdNotMateExceptionHandler:
    """ 处理密码异常 """

    async def __call__(self, request: Request, exc):
        message = exc.detail
        res_code = {
            'code': 200525,
            # 'message': f"{message}不存在"
            'message': f"密码错误"
        }
        return error_res(res_code)


class IntegrityExceptionHandler:
    """ 处理数据库异常 """

    async def __call__(self, request: Request, exc):
        # 定义正则表达式
        pattern = r"Duplicate entry '.+?' for key '(.+?)'"
        # 进行匹配并提取引号内的内容
        match = re.findall(pattern, str(exc))
        content = "无法修改{}数据"
        reservoir_sensitivity.rollback()
        return error_res(ErrorCode.UNIQUE_ERROR, content.format(match))


class StatementErrorExceptionHandler:
    """ 处理sql语句异常 """

    async def __call__(self, request: Request, exc):
        print(str(exc))
        reservoir_sensitivity.rollback()
        if str(exc).find('MySQL server has gone away') != -1:
            return error_res(ErrorCode.SQL_TIMEOUT, "数据库连接已断开，请重试")
        return error_res(ErrorCode.SQL_ERROR, "数据sql语句错误，请重试")


class OperationalErrorExceptionHandler:
    """ 处理sql语句异常 """

    async def __call__(self, request: Request, exc):
        print(str(exc))
        reservoir_sensitivity.rollback()
        if str(exc).find('MySQL server has gone away') != -1:
            return error_res(ErrorCode.SQL_TIMEOUT, "数据库连接已断开，请重试")
        return error_res(ErrorCode.SQL_ERROR, "数据sql语句错误，请重试")


class InvalidRequestErrorExceptionHandler:
    """ 处理sql语句异常 """

    async def __call__(self, request: Request, exc):
        print(str(exc))
        reservoir_sensitivity.rollback()
        if str(exc).find('MySQL server has gone away') != -1:
            return error_res(ErrorCode.SQL_TIMEOUT, "数据库连接已断开，请重试")
        return error_res(ErrorCode.SQL_ERROR, "数据sql语句错误，请重试")

class DataNotExist(HTTPException):
    """ 数据不存在异常 """

    def __init__(self, message: str):
        super().__init__(status_code=500, detail=message)


class DataNotExistExceptionHandler:
    """ 处理数据不存在异常 """

    async def __call__(self, request: Request, exc):
        message = exc.detail
        res_code = {
            'code': 500525,
            'message': f"{message}不存在"
        }
        return error_res(res_code)


class DataNotDelete(HTTPException):
    """ 数据不可删除异常 """

    def __init__(self, message: str):
        super().__init__(status_code=500, detail=message)


class DataNotDeleteExceptionHandler:
    """数据不可删除异常 """

    async def __call__(self, request: Request, exc):
        message = exc.detail
        res_code = {
            'code': 500525,
            'message': f"{message}不可删除"
        }
        return error_res(res_code)


class UserNotActivated(HTTPException):
    """ 用户未激活异常 """

    def __init__(self):
        super().__init__(status_code=500)


class UserNotActivatedExceptionHandler:
    """ 处理用户未激活异常 """

    async def __call__(self, request: Request, exc):
        print(exc.detail)
        return error_res(ErrorCode.USER_NOT_ACTIVATED)


class UserNoPermission(HTTPException):
    """ 用户无权限 """

    def __init__(self):
        super().__init__(status_code=500)


class UserNoPermissionExceptionHandler:
    """ 处理用户无权限异常 """

    async def __call__(self, request: Request, exc):
        message = exc.detail
        return error_res(ErrorCode.USER_NO_PERMISSION)


class LoginCodeException(HTTPException):
    """ 登录验证码错误 """

    def __init__(self, message: str):
        super().__init__(status_code=500, detail=message)


class LoginCodeExceptionHandler:
    """ 处理登录验证码错误 """

    async def __call__(self, request: Request, exc):
        message = exc.detail
        res_code = {
            'code': 500554,
            'message': f"登录验证码{message}"
        }
        return error_res(res_code)
